package com.site.springboot.core.service.impl;

import com.site.springboot.core.entity.News;
import com.site.springboot.core.entity.NewsIndex;
import com.site.springboot.core.repository.NewsIndexRepository;
import com.site.springboot.core.service.NewsService;
import com.site.springboot.core.util.PageQueryUtil;
import com.site.springboot.core.util.PageResult;
import com.site.springboot.core.util.ResultGenerator;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Project:springboot-project-news-publish-system
 * ClassName:NewsIndexService
 * Package:com.site.springboot.core.service.impl
 * User:CWQ
 * Description:
 *
 * @Author 合肥-陈万琼
 * @Create 2024/5/29 0:03
 * @Version 1.0
 */
@Service
public class NewsIndexService {
    private static final Logger log = LoggerFactory.getLogger(NewsIndexService.class);
    @Resource
    private ElasticsearchTemplate template ;
    @Resource
    private NewsService newsService;
    @Resource
    private NewsIndexRepository newsIndexRepository;

    public void initIndex (){
        // 处理索引结构
        IndexOperations indexOps = template.indexOps(NewsIndex.class);
        if (indexOps.exists()){
            boolean delFlag = indexOps.delete();
            log.info("news_index exists，delete:{}",delFlag);
            indexOps.createMapping(NewsIndex.class);
        } else {
            log.info("news_index not exists");
            indexOps.createMapping(NewsIndex.class);
        }

        // 同步数据库表记录
        List<News> contentsList = newsService.queryAll();
        if (contentsList.size() > 0){
            List<NewsIndex> contentsIndexList = new ArrayList<>() ;
            contentsList.forEach(contents -> {
                NewsIndex contentsIndex = new NewsIndex() ;
                BeanUtils.copyProperties(contents,contentsIndex);
                contentsIndexList.add(contentsIndex);
            });
            template.save(contentsIndexList);
        }
        // ID查询
        NewsIndex contentsIndex = template.get("10",NewsIndex.class);
        log.info("contents-index-10:{}",contentsIndex);
    }

    public PageResult getNewsByContent(PageQueryUtil pageUtil,String keywords) {
        int limit = pageUtil.getLimit();
        int page = pageUtil.getPage();
        List<NewsIndex> resultByNewsTitleLike = newsIndexRepository.findByNewsContentLike(keywords);
        PageResult pageResult = new PageResult(resultByNewsTitleLike, resultByNewsTitleLike.size(), limit, page);
        return pageResult;
    }
}
